using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.AccessControl;

namespace SecurityInfoTest
{
    class SecurityInfo
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern int GetSecurityInfo(
            IntPtr handle,
            SE_OBJECT_TYPE objectType,
            SECURITY_INFORMATION securityInfo,
            out IntPtr sidOwner,
            out IntPtr sidGroup,
            out IntPtr dacl,
            out IntPtr sacl,
            out IntPtr securityDescriptor);

        [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
        static extern bool ConvertSidToStringSid(
            IntPtr sid,
            out IntPtr sidString);

        [DllImport("kernel32.dll", SetLastError = true)]
        internal static extern IntPtr LocalFree(
            IntPtr handle
        );

        enum SE_OBJECT_TYPE
        {
            SE_UNKNOWN_OBJECT_TYPE,
            SE_FILE_OBJECT,
            SE_SERVICE,
            SE_PRINTER,
            SE_REGISTRY_KEY,
            SE_LMSHARE,
            SE_KERNEL_OBJECT,
            SE_WINDOW_OBJECT,
            SE_DS_OBJECT,
            SE_DS_OBJECT_ALL,
            SE_PROVIDER_DEFINED_OBJECT,
            SE_WMIGUID_OBJECT,
            SE_REGISTRY_WOW64_32KEY
        }
        enum SECURITY_INFORMATION
        {
            OWNER_SECURITY_INFORMATION = 1,
            GROUP_SECURITY_INFORMATION = 2,
            DACL_SECURITY_INFORMATION = 4,
            SACL_SECURITY_INFORMATION = 8,
        }

        //static void Main(string[] args)
        //{
        //    FileStream fileStream = null;
        //    IntPtr ownerSid;
        //    IntPtr groupSid;
        //    IntPtr dacl;
        //    IntPtr sacl;
        //    IntPtr securityDescriptor = IntPtr.Zero;

        //    int returnValue = 0;
        //    bool success = false;

        //    try
        //    {
        //        fileStream = File.Open(@"C:\Test\Test.txt", FileMode.Open);

        //        returnValue = GetSecurityInfo(fileStream.Handle, SE_OBJECT_TYPE.SE_FILE_OBJECT, SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, out ownerSid, out groupSid, out dacl, out sacl, out securityDescriptor);

        //        IntPtr sidString = IntPtr.Zero;
        //        success = ConvertSidToStringSid(ownerSid, out sidString);
        //        Console.WriteLine(Marshal.PtrToStringAuto(sidString));
        //        Marshal.FreeHGlobal(sidString);
        //    }
        //    finally
        //    {
        //        LocalFree(securityDescriptor);
        //        fileStream.Close();
        //    }
        //}
    }
}
